using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using AutoMapper;
using ExamServer.Models;
using ExamServer.Service;
using ExamServer.Helpers;
using Microsoft.AspNetCore.Mvc;

namespace ExamServer.Controllers
{
  [ApiController]
  [Route("[controller]")]
  public class MenusController : ControllerBase
  {
    private readonly IRepositoryWrapper wrapper;
    private readonly IMapper mapper;

    public MenusController(IRepositoryWrapper wrapper, IMapper mapper)
    {
      this.wrapper = wrapper;
      this.mapper = mapper;
    }

    [HttpGet]
    public async Task<ActionResult> Get(string uid)
    {
      var list = await wrapper.UserHaveMenus.GetMenusByUidAsync(Guid.Parse(uid));
      //var list = await wrapper.Menus.GetAllAsync();
      //从数据库中获取所有菜单     
      if (list != null)
      {
        list = list.DistinctBy(x => x.Id);//去重 使用扩展方法
        var modelList = mapper.Map<IEnumerable<MenusModel>>(list);
        //将数据映射成MenusModel格式

        var firtList = modelList.Where(x => x.Pid == 0).ToList();
        //此处是获取所有一级菜单

        //循环获取其子集
        foreach (var menu in firtList)
        {
          var secondList = modelList.Where(x => x.Pid == menu.Id);
          menu.children = modelList.Where(x => x.Pid == menu.Id);
          //此处是获取所有二级菜单

          foreach (var tmenu in menu.children)
          {
            if (modelList.Count(x => x.Pid == tmenu.Id) > 0)
            //是否存在第三级菜单
            {
              tmenu.children = modelList.Where(x => x.Pid == tmenu.Id);
            }
          }
        }
        JsonResult json = new JsonResult(firtList);
        return json;

      }
      return NotFound();
    }
    [HttpGet]
    [Route("GetAll")]
    public async Task<IActionResult> GetMenusAll()
    {
      var list = await wrapper.Menus.GetAllAsync();
      
      var modelList = mapper.Map<IEnumerable<TreeViewModel>>(list);
      //将数据映射成MenusModel格式

      var firtList = modelList.Where(x => x.Pid == 0).ToList();
      //此处是获取所有一级菜单

      //循环获取其子集
      foreach (var menu in firtList)
      {
        var secondList = modelList.Where(x => x.Pid == menu.id);
        menu.nodes = modelList.Where(x => x.Pid == menu.id);
        //此处是获取所有二级菜单

        foreach (var tmenu in menu.nodes)
        {
          if (modelList.Count(x => x.Pid == tmenu.id) > 0)
          //是否存在第三级菜单
          {
            tmenu.nodes = modelList.Where(x => x.Pid == tmenu.id);
          }
        }
      }
      // if (id != 0 || id != null)
      // { //添加的权限
      //   var roleMenus = await wrapper.Roles.GetRolesById((int)id);
      //   foreach(var menu in firtList){
      //     menu.state.Checked= roleMenus.RolesAndMenus.Count(x=>x.MenuID==menu.id)==1;
      //   }
      // }
      JsonResult json = new JsonResult(firtList);
      return json;
      
    }
  }
}